package com.tianji.learning.service.impl;

import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author leiyuhang
 * @since 2023-07-27
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    private  final InteractionReplyMapper replyMapper;
    private  final IInteractionQuestionService questionService;
    @Override
    public void deleteById(Long id) {
        replyMapper.deleteQuestion(id);
    }

    @Override
    @Transactional
    public void saveReply(ReplyDTO replyDTO) {
        Long user = UserContext.getUser();
        //新增回答
        InteractionReply reply = BeanUtils.toBean(replyDTO, InteractionReply.class);
        reply.setUserId(user);
        save(reply);
        //判断是否为回答
        boolean a = reply.getAnswerId()!=null;
        if (a){
            InteractionReply reply1 = new InteractionReply();
            reply1.setReplyTimes(reply.getReplyTimes()+1);
            reply1.setId(reply.getId());
            updateById(reply1);
        }
        //更新问题表中的状态、 最近一次回答、回答数量

        questionService.lambdaUpdate()
                .set(a, InteractionQuestion::getLatestAnswerId, reply.getAnswerId())
                .setSql(a, "answer_times = answer_times + 1")
                .set(replyDTO.getIsStudent(), InteractionQuestion::getStatus, QuestionStatus.UN_CHECK.getValue())
                .eq(InteractionQuestion::getId, replyDTO.getQuestionId())
                .update();
    }
}
